<template>
  <div class="app-container Center">
      <el-tree
        class="Center"
        :data="data"
        :props="defaultProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-expanded-keys="expandKeys"
        :expand-on-click-node="false"
      >
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span>{{ node.label }}</span>
          <span>
            <el-button type="text" size="mini" @click="() => getCurrentKey(data)">查看</el-button>
            <el-button type="text" size="mini" @click="() => append(data)">添加</el-button>
            <el-button type="text" size="mini" @click="() => remove(node, data)">删除</el-button>
            <el-button type="text" size="mini" @click="() => updateKeyChildren(data)">更新</el-button>
          </span>
        </span>
      </el-tree>

    <!--隐藏表单-->
    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'Edit':'New'">
      <el-form :model="permission" label-width="80px" label-position="left">
        <el-form-item label="英文名称" :rules="{ required: true, message: '非空', trigger: 'blur' }">
          <el-input v-model="permission.name" placeholder="英文名称"/>
        </el-form-item>
        <el-form-item label="中文名称"  :rules="{ required: true, message: '非空', trigger: 'blur' }">
          <el-input v-model="permission.title" placeholder="中文名称"/>
        </el-form-item>
        <el-form-item label="组件" :rules="{ required: true, message: '非空', trigger: 'blur' }">
          <el-input v-model="permission.component" placeholder="组件"/>
        </el-form-item>
        <el-form-item label="路径" :rules="{ required: true, message: '非空', trigger: 'blur' }">
          <el-input v-model="permission.path" placeholder="路径"/>
        </el-form-item>
        <el-form-item label="图标" :rules="{ required: true, message: '非空', trigger: 'blur' }">
          <el-input v-model="permission.icon" placeholder="图标"/>
        </el-form-item>
        <el-form-item label="是否隐藏">
          <el-switch v-model="permission.hidden"></el-switch>
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmPermission">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import { addPermission, deletePermission, getPermission, modifyPermission } from '@/api/permission'
import { deepClone } from '@/utils'
const defaultPermission = {
  id: '',
  pid: '',
  name: '',
  component: '',
  path: '',
  title: '',
  icon: '',
  hidden: ''
}

export default {
  //import引入的组件需要注入到对象中才能使用
  name: "PermissionManager",
  components: {},
  data() {
    //这里存放数据
    const data = [
      {
        id: 1,
        label: "一级 1",
        children: [
          {
            id: 4,
            label: "二级 1-1",
            children: [
              {
                id: 9,
                label: "三级 1-1-1",
              },
              {
                id: 10,
                label: "三级 1-1-2",
              },
            ],
          },
        ],
      },
      {
        id: 2,
        label: "一级 2",
        children: [
          {
            id: 5,
            label: "二级 2-1",
          },
          {
            id: 6,
            label: "二级 2-2",
          },
        ],
      },
    ];
    return {
      data: JSON.parse(JSON.stringify(data)),
      defaultProps: {
        label: 'title',
        children: 'children'
      },
      dialogVisible: false,
      dialogType: 'new',
      permission: Object.assign({}, defaultPermission),
      expandKeys: [],
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    async getPermissionTree() {
      getPermission().then((response) => {
        this.data = response.data.children;
      });
    },
    append(data) {
      this.permission = Object.assign({}, defaultPermission)
      this.permission.pid = data.id
      // console.log(this.permission)
      this.dialogType = 'new'
      this.dialogVisible = true
    },
    updateKeyChildren(data) {
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.permission = deepClone(data)
      this.permission.icon = data.meta.icon
      this.permission.title = data.meta.title
      console.log(this.permission)
    },
    getCurrentKey(data){
      const newMenu=JSON.parse(JSON.stringify(data));
      this.$alert("待补充内容", newMenu.label, {
        confirmButtonText: '确定',
      });
    },
    async confirmPermission() {
      const isEdit = this.dialogType === 'edit'
      if (isEdit) {
        await modifyPermission(this.permission.id, this.permission)
      } else {
        await addPermission(this.permission)
      }
      await this.getPermissionTree()
      this.dialogVisible = false
      this.$notify({
        title: 'Success',
        dangerouslyUseHTMLString: true,
        message: "操作成功",
        type: 'success'
      })
    },
    remove(node, data) {
      const parent = node.parent;
      const children = parent.data.children || parent.data;
      //console.log(JSON.parse(JSON.stringify(data))); //获取对应结点的JSON数据
      deletePermission(data.id, 'FALSE').then(response=>{
        const index = children.findIndex((d) => d.id === data.id);
        children.splice(index, 1);
      })
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getPermissionTree();
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style  scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 17px;
  padding-right: 8px;
}
.Center {
  width: 70%;
}
</style>
